﻿using System;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using eLearning.Model;
using eLearning.Util;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Newtonsoft.Json;

namespace eLearning.View
{
    public partial class PengumumanMatkulPage : PhoneApplicationPage
    {
        private WebClient webClient;
        private object selectedItem;
        private DetailMatkul detMatkul;
        private PengumumanMatkulList dataPengumuman;
        private int currentPage = 1;
        private int displayyed = 5;
        private int dataCount;
        private int limit;

        public PengumumanMatkulPage()
        {
            InitializeComponent();
            detMatkul = null;
            this.Loaded += new RoutedEventHandler(DataContextPage_Loaded);
        }

        private void DataContextPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (PhoneApplicationService.Current.State.ContainsKey(Config.DETMATKUL))
            {
                detMatkul = (DetailMatkul)PhoneApplicationService.Current.State[Config.DETMATKUL];
            }
            if (detMatkul == null)
            {
                detMatkul = new DetailMatkul();
                detMatkul.Creator = (Dosen)SavedUser.Instance.User.ConvertUser();
            }
            LoadPengumumanMatkul(false, JsonConvert.SerializeObject(detMatkul));
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
        }

        private void ManageButton()
        {
            if (SavedUser.Instance.User != null && SavedUser.Instance.User.Type == User.UserType.Dosen
                || SavedUser.Instance.User.Type == User.UserType.Admin)
                ((ApplicationBarIconButton)ApplicationBar.Buttons[0]).IsEnabled = true;
            else
                ((ApplicationBarIconButton)ApplicationBar.Buttons[0]).IsEnabled = false;
        }

        private void LoadPengumumanMatkul(bool search, string json)
        {
            string url = null;

            if (search)
            {
                url = Config.Instance.ANNOUNCE_M_SERVICE_URL() + Config.FIND_ACTION_KEY;
            }
            else
            {
                url = Config.Instance.ANNOUNCE_M_SERVICE_URL() + Config.VIEW_ACTION_KEY;
            }

            string urlformat = string.Format("{0}&{1}", url, Guid.NewGuid().ToString());
            Uri uri = new Uri(urlformat, UriKind.Absolute);

            webClient = new WebClient();

            if (search)
            {
                webClient.Encoding = Encoding.UTF8;
                webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
                webClient.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();
                webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(findPengumumanMatkul_UploadStringCompleted);
                webClient.UploadStringAsync(uri, "POST", json);
            }
            else if (!String.IsNullOrEmpty(json))
            {
                webClient.Encoding = Encoding.UTF8;
                webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
                webClient.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();
                webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(viewPengumumanMatkul_UploadStringCompleted);
                webClient.UploadStringAsync(uri, "POST", json);
            }
            else
            {
                webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(listPengumumanMatkul_DownloadStringCompleted);
                webClient.DownloadStringAsync(uri);
            }
        }

        private void findPengumumanMatkul_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Cancelled || e.Error != null)
                {
                    MessageBox.Show("Message : " + e.Result);
                    return;
                }

                PengumumanMatkulList list = JsonConvert.DeserializeObject<PengumumanMatkulList>(e.Result);
                if (list == null || list.Count <= 0)
                {
                    listPengumumanMatkul.Items.Clear();
                    MessageBox.Show("No announcement found");
                }
                else
                {
                    listPengumumanMatkul.Items.Clear();
                    foreach (PengumumanMatkul p in list)
                    {
                        listPengumumanMatkul.Items.Add(p);
                    }
                    pivotPengumuman.SelectedIndex = 0;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void viewPengumumanMatkul_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Cancelled || e.Error != null)
                {
                    MessageBox.Show("Message : " + e.Result);
                    return;
                }

                dataPengumuman = JsonConvert.DeserializeObject<PengumumanMatkulList>(e.Result);

                dataCount = dataPengumuman.Count;
                currentPage = 0;
                limit = displayyed > dataCount ? dataCount : displayyed;
                DataPaging(currentPage, limit);

                textBlockSize.Text = dataCount.ToString();
                textBlockCurrent.Text = currentPage.ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void listPengumumanMatkul_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Cancelled || e.Error != null)
                {
                    MessageBox.Show("Message : " + e.Result);
                    return;
                }

                dataPengumuman = JsonConvert.DeserializeObject<PengumumanMatkulList>(e.Result);

                dataCount = dataPengumuman.Count;
                currentPage = 0;
                limit = displayyed > dataCount ? dataCount : displayyed;
                DataPaging(currentPage, limit);

                textBlockSize.Text = dataCount.ToString();
                textBlockCurrent.Text = currentPage.ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void NavigateToFormPage()
        {
            Utility.GotoPage(this, "/View/PengumumanMatkulFormPage.xaml");
            FrameworkElement root = Application.Current.RootVisual as FrameworkElement;

            if (pivotPengumuman.SelectedIndex == 0)
            {
                PengumumanMatkul pengumuman = new PengumumanMatkul();
                pengumuman.DetMatkul = detMatkul;
                root.DataContext = pengumuman;
            }
        }

        private void NavigateToDetail(object selectedPengumuman)
        {
            Utility.GotoPage(this, "/View/PengumumanDetailPage.xaml");
            FrameworkElement root = Application.Current.RootVisual as FrameworkElement;
            root.DataContext = selectedPengumuman;
        }

        private void listPengumumanMatkul_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                selectedItem = (PengumumanMatkul)e.AddedItems[0];

                // reset selection of ListBox
                ((ListBox)sender).SelectedIndex = -1;
                NavigateToDetail(selectedItem);
            }
        }

        private void addButton_Click(object sender, EventArgs e)
        {
            NavigateToFormPage();
        }

        private void editButton_Click(object sender, EventArgs e)
        {
            NavigateToDetail(selectedItem);
        }

        private void removeButton_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Remove selected item?", "", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                string json = JsonConvert.SerializeObject(selectedItem);
                Uri uri = new Uri(Config.Instance.ANNOUNCE_M_SERVICE_URL() + Config.DELETE_ACTION_KEY, UriKind.Absolute);
                WebClient client = new WebClient();

                client.Encoding = Encoding.UTF8;
                client.Headers[HttpRequestHeader.ContentType] = "application/json";
                client.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();
                client.UploadStringCompleted += new UploadStringCompletedEventHandler(delete_UploadStringCompleted);

                try
                {
                    client.UploadStringAsync(uri, "POST", json);
                }
                catch (Exception) { }
            }
        }

        private void delete_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Cancelled || e.Error != null)
                {
                    MessageBox.Show("Message : " + e.Result);
                    return;
                }

                if (e.Result.Contains("Success"))
                {
                    MessageBox.Show("Item has been deleted.");
                    LoadPengumumanMatkul(false, "");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("ERROR : " + ex.Message);
            }
        }

        private void searchButton_Click(object sender, EventArgs e)
        {
            pivotPengumuman.SelectedIndex = 1;
        }

        private void refreshButton_Click(object sender, EventArgs e)
        {
            if (detMatkul != null)
                LoadPengumumanMatkul(false, JsonConvert.SerializeObject(detMatkul));
            else
                LoadPengumumanMatkul(false, "");
        }

        private void buttonSearch_Click(object sender, RoutedEventArgs e)
        {
            if (textBoxKeyword.Text.Length < 1)
            {
                MessageBox.Show("Keyword is empty.");
                return;
            }
            Pengumuman find = new Pengumuman();
            find.Info = textBoxKeyword.Text;
            LoadPengumumanMatkul(true, JsonConvert.SerializeObject(find));
        }

        private void textBoxKeyword_TextChanged(object sender, TextChangedEventArgs e)
        {
            buttonClear.IsEnabled = string.IsNullOrEmpty(textBoxKeyword.Text) ? false : true;
            buttonSearch.IsEnabled = string.IsNullOrEmpty(textBoxKeyword.Text) ? false : true;
        }

        private void buttonClear_Click(object sender, RoutedEventArgs e)
        {
            textBoxKeyword.Text = "";
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            ManageButton();

            if (e.NavigationMode == System.Windows.Navigation.NavigationMode.Back)
            {
                if (detMatkul != null)
                    LoadPengumumanMatkul(false, JsonConvert.SerializeObject(detMatkul));
                else
                    LoadPengumumanMatkul(false, "");
            }
        }

        private void DataPaging(int index, int limit)
        {
            listPengumumanMatkul.Items.Clear();
            for (int i = index; i < limit; i++)
            {
                PengumumanMatkul p = dataPengumuman[i];
                listPengumumanMatkul.Items.Add(p);
            }
        }

        private void hyperlinkPrev_Click(object sender, RoutedEventArgs e)
        {
            if (dataPengumuman != null)
            {
                currentPage = (currentPage - displayyed) <= 0 ? 0 : (currentPage - displayyed);
                limit = (currentPage + displayyed) >= dataCount ? dataCount : (currentPage + displayyed);
                DataPaging(currentPage, limit);
                textBlockCurrent.Text = currentPage.ToString();
            }            
        }

        private void hyperlinkNext_Click(object sender, RoutedEventArgs e)
        {
            if (dataPengumuman != null)
            {
                currentPage = (currentPage + displayyed) >= dataCount ? currentPage : (currentPage + displayyed);
                limit = (currentPage + displayyed) >= dataCount ? dataCount : (currentPage + displayyed);
                DataPaging(currentPage, limit);
                textBlockCurrent.Text = currentPage.ToString();
            }            
        }

        private void hyperlinkFirst_Click(object sender, RoutedEventArgs e)
        {
            if (dataPengumuman != null)
            {
                currentPage = 0;
                limit = displayyed >= dataCount ? dataCount : displayyed;
                DataPaging(currentPage, limit);
                textBlockCurrent.Text = currentPage.ToString();
            }            
        }

        private void hyperlinkLast_Click(object sender, RoutedEventArgs e)
        {
            if (dataPengumuman != null)
            {
                currentPage = (dataCount - displayyed) <= 0 ? 0 : (dataCount - displayyed);
                limit = dataCount;
                DataPaging(currentPage, limit);
                textBlockCurrent.Text = currentPage.ToString();
            }            
        }

    }
}